package com.kingmed.kmss.framework.feign.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kingmed.kmss.common.service.sys.RedisService;
import com.kingmed.kmss.common.utils.StringUtils;
import com.kingmed.kmss.common.vo.TextAndCardMessageVo;
import com.kingmed.kmss.framework.feign.config.EnterpriseWeChatConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SendEnterpriseUtil {

    @Autowired
    private RedisService redisService;

    @Autowired
    private EnterpriseWeChatConfig weChatConfig;

    public static final String TOKEN_KEY = "tokenKey";


    public String getAccessToken(){

        // 查询redis，是否存在accessToken，存在则返回redis中的。
        String accessToken = (String) redisService.get(TOKEN_KEY);
        if (StringUtils.isNotEmpty(accessToken)) {
            log.info("redis获取的clientToken：{}，过期时间：{}", accessToken, redisService.getExpire(TOKEN_KEY));
            return accessToken;
        }
        try {
            JSONObject tokenJson = getToken();
            accessToken = tokenJson.getStr("access_token");// token
            Integer expiresIn = tokenJson.getInt("expires_in") - 460; // 超时时间
            log.info("请求企业微信，获取accessToken成功有效时间为:{}", expiresIn + "秒");
            // 存入redis中
            redisService.set(TOKEN_KEY,accessToken,expiresIn);
            return accessToken;
        } catch (Exception e){
            log.error("获取token失败：", e);
            throw new RuntimeException(e);
        }
    }

    public JSONObject getToken(){
        Map<String, Object> map = new HashMap<>();
        map.put("corpid",weChatConfig.corpid);
        map.put("corpsecret",weChatConfig.corpsecret);
        String rep = HttpUtil.get(weChatConfig.accessTokenUrl, map);
        log.info("请求企业微信，得到响应:{}", rep);
        JSONObject parseObj = JSONUtil.parseObj(rep);
        if (0 != parseObj.getInt("errcode")){
            throw new RuntimeException("获取accessToken失败:" + parseObj.get("errmsg"));
        }
        return parseObj;
    }

    public String getUserByMobile(String mobile,String token){
        String url= weChatConfig.getGetUseridUrl() + token;
        JSONObject json = new JSONObject();
        json.put("mobile", mobile);
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            log.error("获取企业用户信息：{}", res);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
                response = JSONUtil.parseObj(result);
                return response.getStr("userid");
            }
            return null;
        } catch (Exception e) {
            log.error("获取企业用户信息失败：", e);
            throw new RuntimeException(e);
        }
    }


    /**
     * @Description 推送文本卡片消息到企业微信
     */
    public String sendTextAndCardMessage(TextAndCardMessageVo messageVo) {
        String url = weChatConfig.getSendMessageUrl() + messageVo.getAccessToken();
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("touser", messageVo.getTouser());
            map.put("totag", messageVo.getTotag());
            map.put("msgtype", messageVo.getMsgtype());
            map.put("agentid", messageVo.getAgentid());//
            map.put("enable_id_trans", "0");
            map.put("enable_duplicate_check", "0");
            map.put("duplicate_check_interval", "1800");
            Map<String, Object> textcard = new HashMap<>(1);
            textcard.put("title", messageVo.getTitle());
            textcard.put("url", messageVo.getUrl());
            textcard.put("description", "<div class=\"gray\">"+messageVo.getDescriptionDate()+"</div> " +
                    "<div class=\"normal\">"+messageVo.getDescriptionMessage()+"</div>" +
                    "<div class=\"highlight\">待您处理，请及时查看。</div>\n");
            map.put("textcard", textcard);
            log.info("推送文本卡片消息参数Map：{}",JSONUtil.toJsonStr(map));
            String data = HttpUtil.post(url, JSONUtil.toJsonStr(map));
            return data;
        } catch (Exception e){
            log.error("推送文本卡片消息到企业微信失败：", e);
            throw new RuntimeException(e);
        }
    }
}
